package cn.sgjk.train.business.controller;


import cn.hutool.core.util.ObjectUtil;
import cn.sgjk.train.business.req.ConfirmOrderDoReq;
import cn.sgjk.train.business.req.ConfirmOrderQueryReq;
import cn.sgjk.train.business.req.ConfirmOrderSaveReq;
import cn.sgjk.train.business.resp.ConfirmOrderQueryResp;
import cn.sgjk.train.business.service.BeforeConfirmOrderService;
import cn.sgjk.train.business.service.ConfirmOrderService;
import cn.sgjk.train.common.exception.BusinessException;
import cn.sgjk.train.common.exception.BusinessExceptionEnum;
import cn.sgjk.train.common.resp.CommonResp;
import cn.sgjk.train.common.resp.PageResp;
import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import jakarta.validation.Valid;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/confirm-order")
public class ConfirmOrderController {

    private static final Logger LOG = LoggerFactory.getLogger(ConfirmOrderController.class);
    @Autowired
    private ConfirmOrderService confirmOrderService;

    @Autowired
    private BeforeConfirmOrderService beforeConfirmOrderService;

    @Autowired
    private RedisTemplate redisTemplate;

    @Value("${spring.profiles.active}")
    private String env;



    @PostMapping("/save")
    public CommonResp<Object> save(@Valid @RequestBody ConfirmOrderSaveReq confirmOrderReq) {
        confirmOrderService.save(confirmOrderReq);
        return new CommonResp<>();
    }

    // 接口的资源名称不要和接口路径一样， 会导致限流后走不到降级方法中
    @SentinelResource(value = "confirmOrderDo",blockHandler = "doComfireBlockExpection")
    @PostMapping("/do")
    public CommonResp<Object> doComfire(@Valid @RequestBody ConfirmOrderDoReq confirmOrderDoReq) {

        if(!env.equals("dev")) {

            //图形验证码
            String imageCodeToken = confirmOrderDoReq.getImageCodeToken();
            String imageCode = confirmOrderDoReq.getImageCode();
            Object imageCodeRedis = redisTemplate.opsForValue().get(imageCodeToken);
            LOG.info("从redis中获取到的验证码:{}",imageCodeRedis);
            if(ObjectUtils.isEmpty(imageCodeRedis)) {
                return  new CommonResp<>(false,"验证码已过期",null);
            }


            // 验证码校验，大小写忽略，提升体验，比如Oo，Ww容易混淆
            if (!imageCodeRedis.toString().equalsIgnoreCase(imageCode)) {
                return new CommonResp<>(false,"验证码错误",null);
            }else{
                //y验证码通过后，移除验证码
                redisTemplate.delete(imageCodeToken);
            }
        }
        Long id = beforeConfirmOrderService.beforeDoConfirm(confirmOrderDoReq);
        LOG.info("confirmOrderDoReq:{}",confirmOrderDoReq);
        return new CommonResp<>(String.valueOf(id));
    }

    @GetMapping("/query-line-count/{id}")
    public CommonResp<Integer> queryLineCount(@PathVariable Long id) {
        Integer count = confirmOrderService.queryLineCount(id);
        LOG.info("当前排在第{}位等出票",count);
        return new CommonResp<>(count);
    }

    public CommonResp<Object> doComfireBlockExpection(ConfirmOrderDoReq confirmOrderDoReq, BlockException e) {
        LOG.info("当前购票被限流:{}",e);
        CommonResp<Object> commonResp = new CommonResp<>();
        commonResp.setSuccess(false);
        commonResp.setMessage(BusinessExceptionEnum.CONFIRM_ORDER_FOLW_EXCEPTION.getDesc());
        return commonResp;
    }



}

